package com.lagou.edu.factory;

import com.lagou.edu.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author 赵乾坤
 * @since 2021-12-04 21:01
 */
@Component("proxyFactory")//bean标签
public class ProxyFactory {

    @Autowired
    private TransactionManager transactionManager;


    /**
     * jdk动态代理
     * @param target 目标对象
     * @return 代理对象
     */
    public Object getProxy(Object target) {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                target.getClass().getInterfaces(), new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[]
                            args) throws Throwable {
                        Object result = null;
                        try {
                            // 开启事务
                            transactionManager.beginTransaction();
                            // 调⽤原有业务逻辑
                            result = method.invoke(target, args);
                            // 提交事务
                            transactionManager.commit();
                        } catch (Exception e) {
                            e.printStackTrace();
                            // 回滚事务
                            transactionManager.rollback();
                            // 异常向上抛出,便于servlet中捕获
                            throw e.getCause();
                        }
                        return result;
                    }
                });
    }
}